package com.capgemini.cn.authority.rest.service.impl;

import com.capgemini.cn.authority.data.entity.GroupMembers;
import com.capgemini.cn.authority.data.entity.Groups;
import com.capgemini.cn.authority.data.repository.GroupMembersRepository;
import com.capgemini.cn.authority.data.repository.GroupsRepository;
import com.capgemini.cn.authority.rest.exception.AuthRestBusinessException;
import com.capgemini.cn.authority.rest.service.AbstractBaseService;
import com.capgemini.cn.authority.rest.service.GroupMemberService;
import com.capgemini.cn.authority.rest.valueobject.DataResponse;
import com.capgemini.cn.authority.rest.valueobject.data.GroupMemberVO;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 2017/9/19
 *
 * @author yaxia
 */
@Service
public class GroupMemberServiceImpl extends AbstractBaseService<GroupMemberVO, GroupMembers> implements GroupMemberService {

    private final String[] IGNORE_PROPERTIES = {
            "groups"
    };

    @Autowired
    @Getter
    @Setter
    private GroupMembersRepository groupMembersRepository;

    @Autowired
    @Getter
    @Setter
    private GroupsRepository groupsRepository;

    @Transactional(readOnly = true)
    @Override
    public DataResponse<List<GroupMemberVO>> findAll(int page, int size, String orderProp, Sort.Direction direction) {
        return null;
    }

    @Transactional(readOnly = true)
    @Override
    public DataResponse<GroupMemberVO> findById(long id) {
        return null;
    }

    @Transactional
    @Override
    public DataResponse<GroupMemberVO> add(GroupMemberVO source) {
        return null;
    }

    @Transactional
    @Override
    public boolean add(List<GroupMemberVO> sourceList) {
        return false;
    }

    @Transactional
    @Override
    public DataResponse<GroupMemberVO> update(long id, Map<String, Object> properties) throws AuthRestBusinessException {
        return null;
    }

    @Transactional
    @Override
    public boolean update(Map<String, Object> properties, List<GroupMemberVO> sourceList) {
        return false;
    }

    @Transactional(readOnly = true)
    @Override
    public DataResponse<List<GroupMemberVO>> findMemberByGroup(Long groupId) throws AuthRestBusinessException {
        Groups groupEntity = this.groupsRepository.findOne(groupId);
        if (ObjectUtils.isEmpty(groupEntity))
            throw new AuthRestBusinessException("无法根据主键ID（" + groupId + "）查询到对应的用户组实体对象信息！");
        List<GroupMembers> groupMembersList = this.groupMembersRepository.findGroupMembersByGroups(groupEntity);
        List<GroupMemberVO> resultList = new ArrayList<>();
        for (GroupMembers entity : groupMembersList)
            resultList.add(this.conversionToValueObject(entity, GroupMemberVO.class));
        return new DataResponse<List<GroupMemberVO>>().setResponse(resultList);
    }

    @Transactional
    @Override
    public DataResponse<GroupMemberVO> bind(String username, long groupId) throws AuthRestBusinessException {
        Groups groupEntity = this.groupsRepository.findOne(groupId);
        if (ObjectUtils.isEmpty(groupEntity))
            throw new AuthRestBusinessException("无法根据主键ID（" + groupId + "）查询到对应的用户组实体对象信息！");
        GroupMembers entity = this.groupMembersRepository.saveAndFlush(new GroupMembers(username, groupEntity));
        return new DataResponse<GroupMemberVO>().setResponse(super.conversionToValueObject(entity, GroupMemberVO.class, this.IGNORE_PROPERTIES));
    }

    @Transactional
    @Override
    public DataResponse<List<GroupMemberVO>> bind(long groupId, String... username) throws AuthRestBusinessException {
        Groups groupEntity = this.groupsRepository.findOne(groupId);
        if (ObjectUtils.isEmpty(groupEntity))
            throw new AuthRestBusinessException("无法根据主键ID（" + groupId + "）查询到对应的用户组实体对象信息！");
        List<GroupMembers> groupMemberList = new ArrayList<>();
        for (String user : username) {
            // 先校验查询当前用户是否已经分配用户组，如果已经分配这直接更新，无分配时再进行创建
            GroupMembers groupMember = this.groupMembersRepository.findByUserName(user);
            if (ObjectUtils.isEmpty(groupMember)) {
                groupMember = new GroupMembers(user, groupEntity);
            } else {
                groupMember.setGroups(groupEntity);
            }
            groupMemberList.add(groupMember);
        }
        groupMemberList = this.groupMembersRepository.save(groupMemberList);
        this.groupMembersRepository.flush();
        return new DataResponse<List<GroupMemberVO>>().setResponse(super.conversionToValueObject(groupMemberList, GroupMemberVO.class, this.IGNORE_PROPERTIES));
    }
}
